const Router = require('koa-router');
const {db, Op,QueryTypes } = require("../../models/db");
const router = new Router();

// 热闹商品
router.post('/zd/getHotList', async ctx => {
    let usr = ctx.user
    let tenantId = usr.tenantId;
    let sql = ` select top 20 invId from (
                                  select invId,count(*) total from invoice a inner join v_main_info b on a.tenantId=b.tenantId and a.tenantId=${tenantId} and a.transType=150601 and a.buId=${usr.buId} group by invId 
                              ) a order by total desc `
    let ret = await db.query(sql, {type: QueryTypes.SELECT})
    let ids = []
    ret.map(row => {
        ids.push(row.invId)
    })
    let recList = []
    if(ids.length > 0) {
        let goodsql = `
        select a.id,a.spec,a.unit1,a.unit2,a.name,a.imgUrl,iif(b.price is null,isnull(a.price2,0),b.price) price,c.sendInvId,c.buyQty,c.sendQty from v_goods a 
            left join (select * from v_price_his_last where tenantId=${tenantId} and buId=${usr.buId}) b on a.tenantId=b.tenantId and a.id=b.invId and a.unit1=b.unit 
            left join (select * from v_send_last where tenantId=${tenantId} and buId=${usr.buId}) c on a.tenantId=c.tenantId and a.id=c.invId 
            where a.tenantId=${usr.tenantId} and a.id in(${ids.join(',')}) 
`
        recList = await db.query(goodsql, {type: QueryTypes.SELECT})

    }
    if(recList.length === 0) {
        let goodsql = `
            select top 8 a.id,a.spec,a.unit1,a.unit2,a.name,a.imgUrl,iif(b.price is null,isnull(a.price2,0),b.price) price,c.sendInvId,c.buyQty,c.sendQty from v_goods a
            left join (select * from v_price_his_last where tenantId=${tenantId} and buId=${usr.buId}) b on a.tenantId=b.tenantId and a.id=b.invId and a.unit1=b.unit
            left join (select * from v_send_last where tenantId=${tenantId} and buId=${usr.buId}) c on a.tenantId=c.tenantId and a.id=c.invId
            where a.tenantId=${usr.tenantId} order by a.ctime desc
        `
        recList = await db.query(goodsql, {type: QueryTypes.SELECT})
    }
    recList.map(row => {
        row.send = ''
        if(row.buyQty) {
            row.send = `买${row.buyQty}赠${row.sendQty}`
        }
    })
    return ctx.suc('', {
        list: recList
    })
})

module.exports = router;
